import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal
from ping import Ui_MainWindow
import threading
import subprocess
import time
from queue import Queue
import tempfile

# 定义sucess列表、工作进程数和初始化队列
ipSuccess = []
# ipFaild = []
Work_Thread = 254
ipQueue = Queue()

# 初始化主窗口类


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.statusbar.showMessage("请按照提示信息操作...")


# 任务逻辑和主窗口进程拆分，防止出现未响应或程序执行时主界面假死

class Work_QThread(QThread):
    trigger = pyqtSignal()

    def __init__(self):
        super(Work_QThread, self).__init__()

    # 处理逻辑
    @pyqtSlot()
    def run(self):

        start_time = time.time()
        ui.statusbar.showMessage("程序执行中...")
        a = ui.ip_line.text()
        for i in range(1, 255):
            ipQueue.put(a + str(i))

        # 获取网段信息并加入队列

        threads = []
        for i in range(Work_Thread):
            thread = threading.Thread(target=pingIp)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()

        # 可以ping通的存入sucess列表
        for i in ipSuccess:
            ip_green = 'ip_' + str(i.split(a)[1])
            ui_info = 'ui.' + ip_green + \
                '.setStyleSheet("background-color:green")'  # 修改UI标签背景为绿色
            eval(ui_info)

        time_info = format(time.time() - start_time, '.2f')
        statusbar_info = '在线台数:' + \
            str(len(ipSuccess)) + ' '*5+'执行耗时:' + time_info + 's'

        # 显示状态栏信息
        ui.statusbar.showMessage(statusbar_info)
        # 清除列表，避免重复统计
        ipSuccess.clear()
        # 发送信号
        self.trigger.emit()


def clear_color():
    # 清除旧颜色
    # background-color: rgb(217, 217, 217) 灰色
    for i in range(1, 255):
        ui_default = 'ui.ip_' + \
            str(i) + '.setStyleSheet("background-color: rgb(217, 217, 217)")'
        eval(ui_default)


@pyqtSlot()
def work():
    a = ui.ip_line.text()
    if len(a) > 0 and len(a.split('.')) == 4 and a.split('.')[-1] == '':
        clear_color()
        workQThread.start()
        # 接受信号，并关联goStop函数
        workQThread.trigger.connect(goStop)

    else:
        # ui.statusbar.showMessage("检测到输入信息不正确，请输入正确的IP网段信息!!")
        QMessageBox.information(ui, "提示信息", "检测到输入信息不正确，请输入正确的IP网段信息。")


@pyqtSlot()
def goStop():
    QMessageBox.information(ui, "提示信息", "操作已成功执行。")
    # print(111)
    # pass


def pingIp():
    # 消费队列里的IP地址
    while not ipQueue.empty():
        ip = ipQueue.get()
        cmd = 'ping -n 2 -w 5 %s' % ip
        # res = subprocess.call(cmd, stdout=subprocess.PIPE)

        out_temp = tempfile.TemporaryFile(mode='w+')
        fileno = out_temp.fileno()
        p = subprocess.call(cmd, stdout=fileno, stderr=fileno)

        # print(ip, True if res == 0 else False)

        # 判断返回值是0（0代表命令成功执行）
        # if res.returncode == 0:
        if p == 0:
            # 成功返回0，将从队列中遍历的IP信息存入成功列表
            ipSuccess.append(ip)


if __name__ == '__main__':
    # 初始化PyQt5窗口
    app = QApplication(sys.argv)
    ui = MyMainWindow()

    workQThread = Work_QThread()
    ui.ping.clicked.connect(work)

    ui.show()
    sys.exit(app.exec_())
